import React from 'react';
import {dark, light} from '../../../config';
import {pxToDp} from '../../../utils/stylesKits';
import {
  Appearance,
  StyleSheet,
  StatusBar,
  Text,
  View,
  SafeAreaView,
  FlatList,
} from 'react-native';
import {Icon, Tabs} from '@ant-design/react-native';
import {connect} from 'react-redux';
import TopSearch from '../../../components/TopSearch';
import ArticleItem from './components/ArticleItem';
import {getJfArticles} from '../../../api/article';

/**
 * APP Home-Index 页面
 * @colorScheme 用户手机主题模式 是否开启了黑夜模式
 * */

const colorScheme = Appearance.getColorScheme() === 'dark' ? dark : light;

const tabs = [
  {title: '关注'},
  {title: '推荐'},
  {title: '热榜'},
  {title: '精选'},
  {title: '后端'},
  {title: '前端'},
  {title: 'android'},
  {title: 'ios'},
];

class Index extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      pageRow: 5,
      articles: [],
      tabPage: 0,
      refreshing: false,
    };
  }
  /**
   * 获取文章列表
   */
  getJfArticles = async () => {
    const {tabPage, articles, pageRow} = this.state;
    if (!articles[tabPage]) {
      articles[tabPage] = {
        list: [],
        count: -1,
        pageIndex: 1,
      };
    }
    const pageIndex = articles[tabPage].pageIndex;
    const data = {pageIndex, pageRow};
    const res = await getJfArticles(data);
    this.setState(() => ({refreshing: false}));
    if (res.data) {
      const articleLsit = {
        list: [...articles[tabPage].list, ...res.data.list],
        count: res.data.count,
        pageIndex: res.data.pageIndex,
      };
      articles[tabPage] = articleLsit;
      this.setState(() => {
        return {
          articles: articles,
        };
      });
    }
  };
  /**
   * tab切换事件触发
   * @param {*tab对象} tab
   * @param {*选中tab索引} index
   * @returns
   */
  changeTabs = async (tab, index) => {
    const {tabPage, articles} = this.state;
    if (tabPage === index) {
      return false;
    }
    await this.setState(() => ({tabPage: index}));
    if (articles[index]) {
      return false;
    }
    await this.getJfArticles();
  };

  /**
   * 下拉刷新事件
   */

  onRefresh = async () => {
    const {tabPage, articles} = this.state;
    articles[tabPage] = null;
    this.setState(() => ({refreshing: true, articles: articles}));
    await this.getJfArticles();
  };

  /**
   * 屏幕触底
   */

  onEndReached = async () => {
    const {tabPage, articles, refreshing} = this.state;
    if (
      articles[tabPage].list.length === articles[tabPage].count ||
      refreshing
    ) {
      return false;
    }
    this.getJfArticles();
  };
  /**
   * 主要内容
   * @param {*tab对象} tab
   * @param {*选中tab索引} index
   * @returns
   */
  renderContent = (tab, tabIndex) => {
    const {articles, refreshing} = this.state;
    return articles.map((articleList, i) => {
      return (
        <SafeAreaView key={i} style={styles.articleList}>
          <FlatList
            style={styles.articleList}
            data={articleList.list}
            renderItem={({item}) => <ArticleItem article={item} />}
            keyExtractor={(article, arti) => arti}
            getItemLayout={(data, index) => ({
              length: pxToDp(140),
              offset: pxToDp(140) * index,
              index,
            })}
            onRefresh={this.onRefresh}
            refreshing={refreshing}
            onEndReachedThreshold={0.1}
            onEndReached={this.onEndReached}
            ListEmptyComponent={() => refreshing || <Text>木有韭菜</Text>}
            ListFooterComponent={() =>
              refreshing || (
                <Text style={styles.listFooterComponent}>没有了~~~</Text>
              )
            }
          />
        </SafeAreaView>
      );
    });
  };

  componentDidMount() {
    this.getJfArticles();
  }

  componentDidUpdate(prevProps, prevState) {}

  componentWillUnmount() {}

  render() {
    const {tabPage} = this.state;
    return (
      <View style={styles.container}>
        <StatusBar
          backgroundColor="transparent"
          barStyle={colorScheme.barStyle}
          translucent={true}
        />
        <View style={styles.topBar}>
          <TopSearch style={styles.topSearch} />
          <Icon name="audio" color={colorScheme.color} size={18} />
          <Text style={styles.topBarBtn}>签到</Text>
        </View>
        <View style={styles.tabBar}>
          <Tabs
            tabs={tabs}
            tabBarBackgroundColor={colorScheme.backgroundColor}
            tabBarInactiveTextColor={colorScheme.color}
            tabBarActiveTextColor="#2387d7"
            tabBarUnderlineStyle={styles.tabBarUnderlineStyle}
            initialPage={0}
            page={tabPage}
            onChange={this.changeTabs}>
            {this.renderContent()}
          </Tabs>
        </View>
      </View>
    );
  }
}

const mapStateToProps = state => ({});
const mapDispatchToProps = {};

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: '100%',
    paddingTop: pxToDp(45),
    backgroundColor: colorScheme.backgroundColor,
  },
  topBar: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
  },
  topSearch: {
    flex: 1,
  },
  topBarBtn: {
    width: pxToDp(50),
    fontSize: pxToDp(16),
    marginLeft: pxToDp(10),
    color: colorScheme.color,
  },
  tabBarUnderlineStyle: {
    width: pxToDp(36),
    marginLeft: pxToDp(20),
  },
  tabBar: {
    flex: 1,
    position: 'relative',
    width: '100%',
  },
  articleList: {
    width: '100%',
    height: '100%',
    backgroundColor: colorScheme.backgroundColorA,
  },
  listFooterComponent: {
    padding: pxToDp(12),
    marginTop: pxToDp(1),
    textAlign: 'center',
    backgroundColor: colorScheme.backgroundColor,
  },
});

export default connect(mapStateToProps, mapDispatchToProps)(Index);
